const App = {
  mixins: [Query], //配置文件，路径/utils/mixins.js
  data() {
    return {
      activeName: "first", //tab页
      photo,
      page: {
        value1: "",
        PageNumber: 1, //页码
        RowAmount: 10,
        Condition: window.btoa(unescape(encodeURIComponent("%%,%%"))),
        ExtensionCondition: window.btoa(
          unescape(
            encodeURIComponent(
              "AND grid_information.Village_Number IN (" +
                getCookie("village") +
                ") AND grid_information.Responsible_Organization IN (" +
                getCookie("unit") +
                ")\r\n"
            )
          )
        ),
      },
      page1: {
        value1: "",
        value2: "",
        value3: "",
        SQLSerialNumber: "t_grid_member1",
        PaginationNumber: 1, //页码
        RowAmount: 10,
        Condition: window.btoa(unescape(encodeURIComponent("%%,%%,%%"))),
        ExtensionCondition: window.btoa(
          unescape(
            encodeURIComponent(
              "AND grid_information.Village_Number IN (" +
                getCookie("village") +
                ") AND grid_information.Responsible_Organization IN (" +
                getCookie("unit") +
                ")\r\n"
            )
          )
        ),
      },
      Total1: 0,
      Tabletdata1: [],
      grid_member_type: [],
      isShow: true,
      str1: "",
      str2:
        "AND grid_information.Village_Number IN (" +
        getCookie("village") +
        ") AND grid_information.Responsible_Organization IN (" +
        getCookie("unit") +
        ")\r\n",
      tab: [
        {
          label: "网格管理",
          name: "first",
          TableName: "grid_information",
          primary_key: "Grid_SerialNumber",
        },
        {
          label: "网格人员管理",
          name: "second",
          TableName: "grid_member",
          primary_key: "Grid_Member_SerialNumber",
        },
      ],
      ProvinceNumber: "",
      grid_member: {},
    };
  },
  mounted() {
    // let obj = {
    //   SQLSerialNumber: "s_base_sql_table_config",
    //   Condition: window.btoa( unescape(encodeURIComponent("%%"))),//路径（默认查询的）
    //   ExtensionCondition:window.btoa( unescape(encodeURIComponent("AND base_sql_list.SQL_SerialNumber='aaa'"))),//sql标识（指定查询）
    // };
    $.ajax({
      headers: requestHeaders(),
      url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
      method: "post",
      data: {
        Data: 'grid_member_type',
        Condition: `Row_Status='0'`,
      },
      success: (res) => {
        this.grid_member_type = res
      },
      complete: (XMLHttpRequest) => {
        requestPretreatment(XMLHttpRequest)
      },
    });
    this.postgetList1(this.page1);
  },
  computed: {
    gridzz() {
      return function (str) {
        try {
          let arr = this.grid_member[str];
          let obj = arr.filter((i) => i.Role == "2")[0];
          if (obj) {
            return obj;
          }
        } catch (error) {}
        return { Personal_Name: "", Contact_Phone: "", Picture_URL: "" };
      };
    },
    grid() {
      return function (str) {
        let arr = this.grid_member[str];
        if (arr) {
          return arr;
        }
        return [];
      };
    },
  },
  methods: {
    // 导出方法
    Batchexport() {
      const that = this;
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
        method: "post",
        data: {
          SQLSerialNumber: "s_base_sql_table_config",
          Condition: window.btoa(
            unescape(encodeURIComponent("%" + this.relativePath + "%"))
          ),
          ExtensionCondition: "",
        },
        success: (columns) => {
          console.log(columns);
          $.ajax({
            headers: requestHeaders(),
            method: "post",
            url: mh + "/generalBusiness/generalQueryBySQLSerialNumber",
            data: {
              Model_Url: this.relativePath,
              Condition: this.page.Condition,
              ExtensionCondition: this.page.ExtensionCondition || "",
            },
            success: (data) => {
              if (data.length > 0) {
                this.$confirm(
                  `当前共查出${data.length}条数据, 是否继续?`,
                  "提示",
                  {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "success",
                  }
                )
                  .then(() => {
                    console.log("点击了确认");

                    this.$prompt("请输入您导出的文件名", "提示", {
                      confirmButtonText: "确定",
                      cancelButtonText: "取消",
                    })
                      .then(({ value }) => {
                        this.$message({
                          type: "success",
                          message: "你的文件名是: " + value,
                        });
                        if (!value) {
                          value = "未知名";
                        }
                        // return;
                        const wb = XLSX.utils.book_new();
                        const ws_data = [columns.map((i) => i.COLUMN_COMMENT)];
                        const ws_main = data.map((item) =>
                          columns.map((row) => item[row.COLUMN_NAME])
                        );
                        const ws = XLSX.utils.aoa_to_sheet([
                          ...ws_data,
                          ...ws_main,
                        ]);
                        ws["!cols"] = [];
                        for (
                          let i = 0;
                          i < Object.keys(ws_data[0]).length;
                          i++
                        ) {
                          ws["!cols"].push({ wpx: 150 });
                        }
                        XLSX.utils.book_append_sheet(wb, ws, value);
                        XLSX.writeFile(wb, value + ".xlsx");
                      })
                      .catch(() => {
                        this.$message({
                          type: "info",
                          message: "取消输入",
                        });
                      });
                  })
                  .catch((erro) => {
                    console.log(erro);
                  });
              } else {
                this.$message({
                  message: "未查询出可导出的数据!",
                  type: "warning",
                });
              }
            },
            complete: (XMLHttpRequest) => {
              requestPretreatment(XMLHttpRequest);
            },
          });
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
      });
    },
    pelAdd() {
      window.location.href = "add1.html?action=Add";
    },
    handleSizeChange1(newSize) {
      this.page1.PaginationNumber = 1;
      this.page1.RowAmount = newSize;
      this.postgetList1(this.page1);
    },
    handleCurrentChange1(newPage) {
      this.page1.PaginationNumber = newPage;
      this.postgetList1(this.page1);
    },
    handleClick(tab) {
      //   if (tab.index == 0) {
      //   } else {
      //   }
      //   this.getList(tab.index);
    },
    getList(id = 0) {
      const that = this;
      let data = {};
      if (id == 0) {
        data = {
          SQLSerialNumber: "s_base_sql_table_config",
          Condition: window.btoa(
            unescape(encodeURIComponent("%" + this.relativePath + "%"))
          ),
          ExtensionCondition: "",
        };
      } else {
        data = {
          SQLSerialNumber: "s_base_sql_table_config",
          Condition: window.btoa(unescape(encodeURIComponent("%%"))),
          ExtensionCondition: window.btoa(
            unescape(
              encodeURIComponent(
                "AND base_sql_list.SQL_SerialNumber='t_grid_member'"
              )
            )
          ),
        };
      }
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
        method: "post",
        data,
        success: (data) => {
          that.columns = data;
          that.checkedFields = data;
          that.fields = data;
          that.loading = true;
          that.postgetList(that.page);
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
      });
    },
    postgetList1(data) {
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalPaginationQueryBySQLSerialNumber`,
        method: "post",
        data,
        success: (res) => {
          this.Total1 = res.TotalRows; //总数量
          res.Rows.forEach((item) => {
            item.grid_member = [];
          });
          this.Tabletdata1 = res.Rows;
          submitSave({
            Add: {
              base_operation_log: [
                {
                  Operation_Type: "0",
                  Operation_Path: this.relativePath,
                  Operation_Main: JSON.stringify(
                    deepClone({
                      Data: res.Rows,
                      Param: data,
                    })
                  ),
                  Operation_Interface:
                    "generalPaginationQueryBySQLSerialNumber",
                  Operation_IP: getIpAddress(),
                },
              ],
            },
          });
          // $.ajax({
          //   headers: requestHeaders("JSON"),
          //   url: `${mh}/generalBusiness/generalSaveByRequestBody`,
          //   method: "post",
          //   data: JSON.stringify({
          //     Data: {
          //       Add: {
          //         base_operation_log: [{
          //           Operation_Type: '0',
          //           Operation_Path: this.relativePath,
          //           Operation_Main: JSON.stringify(deepClone({
          //             Data: res.Rows,
          //             Param: data
          //           })),
          //           Operation_Interface: "generalPaginationQueryBySQLSerialNumber",
          //           Operation_IP: getIpAddress()
          //         }]
          //       }
          //     },
          //   }),
          //   complete: (XMLHttpRequest) => {
          //     requestPretreatment(XMLHttpRequest)
          //   }
          // });
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
      });
    },
    Treedata() {
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/permissionsTree/getDistrictTreeByPermissions`,
        type: "GET",
        data: {
          DistrictCode: getCookie("village"), //请求参数
        },
        success: (data) => {
          this.treeData = data;
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
        dataType: "json",
      });
    },
    check() {
      if (this.activeName == 'first') {
        this.page.Condition = window.btoa(unescape(encodeURIComponent("%%,%" + this.page.value1 + "%")));
        this.postgetList(this.page);
      } else {
        this.page1.Condition = window.btoa(unescape(encodeURIComponent("%"+this.page1.value1+"%,%" + this.page1.value2 + "%,%" +  this.page1.value3 + "%")));
        this.postgetList1(this.page1);
      }
    },
    handleAdd(row) {
      let { primary_key } = JSON.parse(
        document.getElementById("table").getAttribute("data-options")
      );
      window.location.href =
        "./add.html?action=Add&nodeKey=" + row[primary_key];
    },
    handleAdd1(row) {
      window.location.href =
        "./add.html?action=Add&ProvinceNumber=" + row.ProvinceNumber;
    },
    handleMember(row) {
      let { primary_key } = JSON.parse(
        document.getElementById("table").getAttribute("data-options")
      );
      window.location.href =
        "./add1.html?action=Modify&nodeKey=" + row[primary_key];
    },
    handleMember1(row) {
      let { primary_key } = JSON.parse(
        document.getElementById("table").getAttribute("data-options")
      );
      window.location.href =
        "./add2.html?action=Modify&nodeKey=" + row[primary_key];
    },
    handleMember2(row) {
      let { primary_key } = JSON.parse(
        document.getElementById("table").getAttribute("data-options")
      );
      window.location.href =
        "./add3.html?action=Modify&nodeKey=" + row[primary_key];
    },
    ExpandChange(row) {
      $.ajax({
        headers: requestHeaders(),
        url: `${mh}/generalBusiness/generalQueryBySQLSerialNumber`,
        method: "post",
        data: {
          SQLSerialNumber: "t_grid_member",
          Condition: "",
          ExtensionCondition: window.btoa(
            unescape(
              encodeURIComponent(
                `AND grid_member.Grid_SerialNumber='${row.Grid_SerialNumber}'`
              )
            )
          ),
        },
        success: (data) => {
          this.grid_member[row.Grid_SerialNumber] = data;
        },
        complete: (XMLHttpRequest) => {
          requestPretreatment(XMLHttpRequest);
        },
      });
    },
    //树的点击筛选事件
    handleNodeClick(data, node) {
      this.ProvinceNumber = data.ProvinceNumber;
      let arr = [],
        str = "";
      if (data.children) {
        this.Organization(data.children, arr);
      }
      [data.ProvinceNumber, ...arr].forEach((item) => {
        if (str) {
          str +=
            "\r\nOR grid_information.Parent_Grid_SerialNumber='" + item + "'";
        } else {
          str = "\r\ngrid_information.Parent_Grid_SerialNumber='" + item + "'";
        }
      });
      if (str) {
        str = "AND (" + str + ")";
      }
      this.str1 = str;
      this.page.ExtensionCondition = window.btoa(
        unescape(encodeURIComponent(this.str1 + this.str2))
      );
      this.postgetList(this.page);
    },
    Organization(data, arr) {
      data.forEach((item) => {
        arr.push(item.ProvinceNumber);
        if (item.children && item.children.length > 0) {
          this.Organization(item.children, arr);
        }
      });
    },
  },
};

const { createApp } = Vue;
const app = createApp(App);
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
const ElMessage = ElementPlus.ElMessage;
app.use(ElementPlus, { locale: zhCn });
app.mount("#app");
